﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;
using TSL_Tools.SqlTools;
using ReportingEngine;
using System.IO;
using System.Windows.Forms.DataVisualization.Charting;
using System.Xml;
using System.ComponentModel;
using System.Drawing;

namespace VSLT_Reporting
{
    public partial class MainWindow : Window
    {
        public static readonly string Sql_SUMMARY_TESTRESULTS = @"EXEC TSL_prc_Summary_TestResults @runId = {0}, @NameFilter = {1},
            @StartOffset = {2}, @EndOffset = {3}, @IncludeFailedTests = {4}, @OrderByAverageTime = {5}, @IncludeWarmupCooldown = {6}, @NumberOfRows = {7}";

        public static readonly string Sql_SUMMARY_TRANSACTIONRESULTS = @"EXEC TSL_prc_Summary_TransactionResults @runId = {0}, @NameFilter = {1},
            @StartOffset = {2}, @EndOffset = {3}, @IncludeFailedTransactions = {4}, @OrderByAverageTime = {5}, @IncludeWarmupCooldown = {6}, @NumberOfRows = {7}";

        public static readonly string Sql_SUMMARY_PAGERESULTS = @"EXEC TSL_prc_Summary_PageResults @runId = {0}, @NameFilter = {1},
            @StartOffset = {2}, @EndOffset = {3}, @IncludeFailedPages = {4}, @OrderByAverageTime = {5}, @IncludeWarmupCooldown = {6}, @NumberOfRows = {7}";

        /// <summary>
        /// Parameter 0: LoadTestRunId
        /// Parameter 1: RequestUri
        /// </summary>
        public static readonly string Sql_GETPERFMON_PAGESAMPLES = @"EXEC TSL_prc_PerfCounterValuesFromPageSamples @RunId = {0}, @RequestUri = N'{1}'";

        /// <summary>
        /// Parameter 0: LoadTestRunId
        /// Parameter 1: TransactionName
        /// </summary>
        public static readonly string Sql_GETPERFMON_TRANSACTIONSAMPLES = @"EXEC TSL_prc_PerfCounterValuesFromTransactionSamples @RunId = {0}, @TransactionName = N'{1}'";

        /// <summary>
        /// Parameter 0: LoadTestRunId
        /// Parameter 1: TestCaseName
        /// </summary>
        public static readonly string Sql_GETPERFMON_TESTCASESAMPLES = @"EXEC TSL_prc_PerfCounterValuesFromTestCaseSamples @RunId = {0}, @TestCaseName = N'{1}'";


        private void AddPerfmonCounterTableAndChartToReport(string name)
        {
            DateTime dt = DateTime.Now;
            // ----- Get the data to build table and chart -----
            DataTable _table = new DataTable();
            GenerateRunData(TSL_ReportingEngine.Sql_SUMMARY_TESTRESULTS, ref _table, true, name);

            // THIS BUILDS THE CHART AND PASTES IT INTO THE DOCUMENT
            BuildPerfmonCounterTimingChart(ref _table);
            // This builds the table that acts as a legend and a summary
            FlowDocument flowDocTemp = CreateXamlChartTableFromDataTable(name, _table, new List<int>(new int[] { 400, 50, 50, 50, 50, 50, 50, 50, 50, 50 }));

            rtbResults.Document.Blocks.Add(flowDocTemp.Blocks.FirstBlock);
            AddSeparatorLinesToReport(1);

            rtbResults.UpdateLayout();

            //AddDebugTimingInfo((TimeSpan)(DateTime.Now - dt), " -- AddCoreTestCaseTableAndChartToReport");
        }

        private void BuildPerfmonCounterTimingChart(ref DataTable testItems)
        {
            tsslMessage.Content = String.Format("Building Test Timing Chart");

            Chart chart = this.FindName("MyWinformChart") as Chart;
            LoadChartTemplate(ref chart, Properties.Settings.Default.ChartTemplateName);
            chart.Titles[0].Text = Msg_CHART_TESTTIMETITLE;
            ClearChartObjectList();

            AddDebugTimingInfo(GetPerfmonCounterChartObjects(ref testItems), " -- GetPerfmonCounterChartObjects Total Time");
            AddCurrentChartToReport();
        }

        private TimeSpan GetPerfmonCounterChartObjects(ref DataTable chartItems)
        {
            DateTime dt = DateTime.Now;
            string sqlConn = Properties.Settings.Default.sqlConn;
            currentPlotColor = 0;

            // Name	                        Passed	Minimum	Average	Maximum	Std Dev	90Percent	95Percent
            // Single Project_ViewAll_OFF	150	    154.41	166.71	185.54	6.67	175.94	    179.55
            for (int x = 0; x < chartItems.Rows.Count; x++)
            {
                string sqlCmd = String.Format(TSL_ReportingEngine.Sql_GETPERFMON_TESTCASESAMPLES, currentlyHighlightedRunId, chartItems.Rows[x][0].ToString());
                DataTable _table;
                TimeSpan ts = tts.ExecuteReaderTable(sqlCmd, out _table);
                AddDebugTimingInfo(ts, " --\tCoreTestChartObjects " + sqlCmd);
                mostRecentSqlQuery = sqlCmd;

                TSL_ChartingDataSeries series = new TSL_ChartingDataSeries();
                series.runId = currentlyHighlightedRunId;
                series.fullCounterName = String.Format("{0}_{1}", chartItems.Rows[x][0], x);
                series.name = "Avg. Test Time";
                series.machineName = re.listOfRuns[currentlyHighlightedRunId].controllerName;
                series.categoryName = "LoadTest:Test";
                series.counterName = "Avg. Test Time";
                series.instanceName = "_Total";
                series.lineColor = plotColors[currentPlotColor % plotColors.Count];
                series.chartObjectScale = 0;
                series.intervalSpan = re.listOfRuns[currentlyHighlightedRunId].sampleRate;
                currentPlotColor++;
                series.minValue = (decimal)chartItems.Rows[x]["Minimum"];
                series.averageValue = (decimal)chartItems.Rows[x]["Average"];
                series.maxValue = (decimal)chartItems.Rows[x]["Maximum"];
                series.stdDev = (decimal)chartItems.Rows[x]["Std Dev"];
                series.ninetyPct = (decimal)chartItems.Rows[x]["90Percent"];
                series.ninetyFivePct = (decimal)chartItems.Rows[x]["95Percent"];
                series.testIntervalValues = _table.Copy();
                AddChartSeriesItems(series);
            }

            return (TimeSpan)(DateTime.Now - dt);
        }
    }
}
